package controllers

import (
	"HTanfang/htmodels"
	"anfang/models"
	"github.com/astaxie/beego"
	"strings"
	"HTanfang/mqtt_server"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.TplName = "index.html"
}

func (c *MainController) Index_v1() {
	c.TplName = "index_v1.html"
}
func (c *MainController) Login() {
	if uid := c.GetSession("uid"); uid != nil {
		c.Redirect("/", 302)
	}
	phone := c.GetString("user")
	pass := c.GetString("pass")
	if phone == "admin@admin.com" {
		if pass == "admin123" {
			c.SetSession("uid", 0)
			c.SetSession("utype", 1000)
			c.Redirect("/", 302)
		}
	}
	if phone != "" {
		user := models.Users{Username: phone}
		emailOrPhone := false
		if strings.Index(phone, "@") != -1 {
			emailOrPhone = true
		}
		if htmodels.HTCheckUserLogin(&user, phone, pass, emailOrPhone) {
			c.SetSession("uid", user.Id)
			c.SetSession("utype", user.UserType)
			c.Redirect("/", 302)
		} else {
			c.Data["wronginfo"] = true
		}
	}

	c.TplName = "login.html"
}

func (c *MainController) Logout() {
	c.DelSession("uid")
	c.DelSession("utype")
	c.Redirect("/login", 302)
}

func (c *MainController) PushTest() {
	lock, _ := c.GetInt("lock")
	topic := "/test/unlock"
	lockStr := "unlock"
	if lock != 0 {
		topic = "/test/lock"
		lockStr = "lock"
	}
	mqtt_server.PushMessage(topic, lockStr)
	Json_Message(&c.Controller, 0, "suc")
}
